package com.scs.application.modules.base.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Certificate;
import com.scs.application.modules.base.service.CertificateService;
import com.scs.application.modules.sys.model.RestResult;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 资质预警表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/base/certificate")
public class CertificateController extends CrudController<CertificateService, Certificate>{
    /**
     *资质效期自动预警
     * */
    @PostMapping("/autoEarlyWarning")
    public RestResult autoEarlyWarning() {
        service.autoEarlyWarning();
        return RestResult.ok();
    }
    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Certificate entity) {
        Boolean closeFlag = false;//默认正常状态
        if (entity.getCloseFlag() != null) {
            closeFlag = entity.getCloseFlag();
            if (!closeFlag) {//如果是正常的状态，要先去数据库里面检查这个厂商或者供应商的该种资质有没有存在正常的数据
                Certificate old  = service.getOne(Wrappers.<Certificate>query().eq("target_id",entity.getTargetId()).eq("certificate_type",entity.getCertificateType()).eq("close_flag",0));
                if (null != old) {
                    throw new BusinessException("对不起， " + old.getTargetName() + " 已经存在 " + old.getCertificateName() + " 状态为： 正常 的资质数据！");
                }
            }
        }
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String dayStr = sf.format(new Date());
        String today = dayStr + " 23:59:59";
        Date todayDate ;
        StringBuilder oldOutName = new StringBuilder();
        try {
            todayDate = DateUtils.parse(today,"yyyy-MM-dd HH:mm:ss");

            if (DateUtils.addDays(todayDate, -1).compareTo(entity.getExpiryDate()) >= 0 && !closeFlag) {
                service.updateMatrForbiddenByCertificate(entity, 1);//把已经到期的资质对应的所有耗材都设置为禁用状态
            }
            if (DateUtils.addDays(todayDate, -1).compareTo(entity.getExpiryDate()) < 0 && !closeFlag) {
                //这时候还要去查一下当前厂商或者供应商的所有资质中是否还有已经过期的资质
                List<Certificate> oldOuts = service.list(Wrappers.<Certificate>query().eq("target_id",entity.getTargetId()).le("expiry_date",DateUtils.addDays(todayDate, -1)).eq("close_flag",0));
                if (CollectionUtils.isEmpty(oldOuts)) {//所有资质中没有已经过期的资质时才去更新对应的耗材禁用属性
                    service.updateMatrForbiddenByCertificate(entity, 0);//把已经到期的资质对应的所有耗材都设置为非禁用状态
                } else {
                    oldOuts.stream().forEach(certificate -> oldOutName.append(certificate.getCertificateName()).append("-" + certificate.getCertificateCode() + " "));
                }
            }
        } catch (ParseException e) {
            logger.error("数据保存异常，{}", e);
            throw new BusinessException("对不起，程序异常");
        }
        if (StringUtils.isNotBlank(oldOutName.toString())) {
            oldOutName.append(" 仍然是过期状态，请注意！");
        }
        oldOutName.append(" ");
        return RestResult.ok("数据保存成功 " + oldOutName.toString(), entity);
    }
}
